package com.example.exception;

import com.example.common.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 * 使用 JDK 21 优化，采用现代化异常处理方式
 */
@RestControllerAdvice(basePackages = "com.example.controller")
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(CustomException.class)
    public Result handleCustomException(HttpServletRequest request, CustomException e) {
        log.warn("业务异常 [{}] - {}: {}", request.getRequestURI(), e.getCode(), e.getMsg());
        return Result.error(e.getCode(), e.getMsg());
    }

    /**
     * 处理系统异常
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(HttpServletRequest request, Exception e) {
        log.error("系统异常 [{}]: ", request.getRequestURI(), e);
        return Result.error();
    }
}
